package com.ccm.demo.springbootsecurity.security;

import com.ccm.demo.springbootsecurity.entity.SysMenu;
import com.ccm.demo.springbootsecurity.entity.SysRole;
import com.ccm.demo.springbootsecurity.service.MenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
@Component
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	@Resource
	private MenuService menuService;

	AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Override
	public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
		//获取请求地址
		String requestUrl = ((FilterInvocation) o).getRequestUrl();
		if ("/login".equals(requestUrl)) {
			return null;
		}
		List<SysMenu> allMenu = menuService.getAllMenu();
		for (SysMenu sysMenu : allMenu) {
			if (antPathMatcher.match(sysMenu.getMenuUrl(), requestUrl)&&sysMenu.getSysRoles().size()>0) {
				List<SysRole> roles = sysMenu.getSysRoles();
				int size = roles.size();
				String[] values = new String[size];
				for (int i = 0; i < size; i++) {
					values[i] = roles.get(i).getRoleName();
				}
				return SecurityConfig.createList(values);
			}
		}
		//没有匹配上的资源，都是登录访问
		return SecurityConfig.createList("ROLE_LOGIN");
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> aClass) {
		return FilterInvocation.class.isAssignableFrom(aClass);
	}
}
